/**
 * 切换主题Drawer
 * */
import React, { useEffect, useMemo, useState } from 'react';
import { connect } from 'umi';
import { Col, Drawer, message, Row, Space, Tooltip } from 'antd';
import { CheckOutlined } from '@ant-design/icons';
import '@/components/GlobalHeader/styles.less';
import { HeaderAPI } from '@/components/GlobalHeader/type';
import ScrollBarLayout from '@/components/ScrollBarLayout';
import { getTheme, setTheme, getUserID, getThemeFontSize, setThemeFontSize } from '@/utils/authority';
import cls from 'classnames';

import { onChangeTheme } from '@/utils';
import MyIcon from '@/components/MyIcon';
import { editThemeService } from '../services';

const SwitchTheme: React.FC<HeaderAPI.IThemePropsType> = ({ visible, onClose, dispatch, settings, setLayoutSettings }) => {
  const [themeList, setThemeList] = useState<Record<string, any>[]>([]);
  const [themeID, setThemeID] = useState(getTheme());
  const [themeStyle, setThemeStyle] = useState(settings?.layout == 'top' ? 1 : 0);

  const themeFontSizeValue: string | number | any = getThemeFontSize() ? Number(getThemeFontSize()) : 14;

  /** 字号切换 */
  const FONTCLS = 'change-fontsize';

  useEffect(() => {
    if (visible) {
      dispatch({
        type: 'baseLogin/getSwitchThemeList',
        callback: (res: any) => {
          if (res && res?.msgFlag) {
            setThemeList(() => {
              return res.obj.filter((item) => item.name != '火山' && item.name != '法式洋红' && item.name != '薄暮');
            });

            /** 获取主题详情初始化字号 */
            // getThemeInfoFont(res?.obj);
          } else {
            message.error(res?.msg);
          }
        },
      });
    }
  }, [visible, getTheme()]);

  /* 切换主题 */
  const changeTheme = (id: any, themeType: any) => {
    const fontSizeValue: string | any = getThemeFontSize() ? getThemeFontSize() : 14;
    if (id) {
      dispatch({
        type: 'baseLogin/switchTheme',
        payload: {
          id: getUserID(),
          themeID: id,
          themeType: themeType,
          themeFont: fontSizeValue,
        },
        callback: (res: any) => {
          if (res && res?.msgFlag) {
            let nowTheme = themeList.find((i: any) => i?.id === id);
            onChangeTheme(nowTheme?.defaultStyle, fontSizeValue);
            setTheme(id);
            setThemeID(id);
            onClose();
          } else {
            message.error(res?.msg);
          }
        },
      });
    }
  };

  /* 切换Layout 布局 */
  const onSwitchLayout = (key: 'top' | 'side', type: 0 | 1) => {
    setThemeStyle(type);

    if (key) {
      setLayoutSettings({
        ...settings,
        layout: key,
      });
      changeTheme(themeID, type);
      onClose();
    }
  };

  /** 主题编辑回调 */
  const editThemeCallback = (res: any) => {
    if (res && res?.msgFlag) {
      changeTheme(themeID, themeStyle);
      onClose();
    } else {
      message.error(res?.data?.msg);
    }
  };

  // /** 编辑主题 */
  // const { editThemeRun } = editThemeService(editThemeCallback);

  /**
   * 判断当前选中
   * @param sizeValue
   * @returns
   */
  const isFontSizeBool = (sizeValue: number) => {
    return themeFontSizeValue == sizeValue;
  };

  /**
   * 字体改变
   * @param sizeValue
   */
  const fontSizeChange = (sizeValue: string) => {
    setThemeFontSize(sizeValue);
    changeTheme(themeID, themeStyle);

    // const currentThemeInfo: Record<string, any> | any = themeList?.find((item: any) => item?.id == themeID);

    // /** 主题参数 */
    // const themeParams = {
    //   id: themeID,
    //   name: currentThemeInfo?.name,
    //   themeStyle: {
    //     ...currentThemeInfo?.themeStyle,
    //   },
    //   defaultStyle: {
    //     ...currentThemeInfo?.defaultStyle,
    //   },
    //   versionNum: currentThemeInfo?.versionNum ?? 0,
    //   seq: 0,
    // };
    // editThemeRun(themeParams);
  };

  /** 返回主题色彩 */
  const returnThemeColor = useMemo(() => {
    if (themeList?.length > 0 && themeID) {
      const themeInfo: Record<string, any> | any = themeList?.find((item: any) => item?.id == themeID);
      return themeInfo?.defaultStyle?.['@primary-color'] || '#dbdbdb';
    }
    return '#dbdbdb';
  }, [themeID, themeList]);

  return (
    <Drawer
      open={visible}
      onClose={onClose}
      bodyStyle={{ overflow: 'auto', padding: 0 }}
      width={window.screen.width * 0.23}
      forceRender={false}
      destroyOnClose={true}
      closable={false}
    >
      <ScrollBarLayout>
        <div className={cls('header-theme')}>
          <p>导航模式</p>
          <div className={cls('base-menu-view')}>
            <Tooltip placement={'top'} title={'侧边布局'}>
              <div
                className={cls('base-menu-nav')}
                onClick={() => {
                  onSwitchLayout('side', 0);
                }}
              >
                <div className={cls('base-nav-left')}></div>
                <div className={cls('base-nav-top')}></div>
              </div>
            </Tooltip>

            <Tooltip placement={'top'} title={'头部布局'}>
              <div
                className={cls('base-menu-top')}
                onClick={() => {
                  onSwitchLayout('top', 1);
                }}
              >
                <div className={cls('base-top-top')}></div>
              </div>
            </Tooltip>
          </div>
          <p>主题设置</p>
          <Row gutter={[0, 10]} style={{ marginBottom: 16 }}>
            {themeList?.length > 0 &&
              themeList?.map((item) => {
                return (
                  <Col span={6} key={item?.id}>
                    {item?.defaultStyle?.['@primary-color'] && (
                      // <Tooltip title={item?.name} placement={'top'}>
                      <div
                        className={cls('header-theme-colorItem')}
                        onClick={() => {
                          if (!(item?.id == themeID)) {
                            changeTheme(item?.id, themeStyle);
                          }
                        }}
                        style={{
                          cursor: item?.id == themeID ? 'no-drop' : 'pointer',
                        }}
                      >
                        <div
                          className={cls('header-theme-block')}
                          style={{
                            background: item?.defaultStyle?.['@primary-color'],
                          }}
                        >
                          {item?.id == themeID && <CheckOutlined style={{ color: '#ffffff', fontSize: 18 }} />}
                        </div>
                        <div
                          style={{
                            color: item?.defaultStyle?.['@primary-color'],
                          }}
                        >
                          {item?.name}
                        </div>
                      </div>
                      // {/* </Tooltip> */}
                    )}
                  </Col>
                );
              })}
          </Row>

          <p>字号设置</p>
          <Space className={`${FONTCLS}-fontSizeLayout`} direction="vertical">
            <dl
              style={{
                fontSize: '14px',
                borderColor: isFontSizeBool(14) && returnThemeColor,
              }}
              onClick={() => {
                if (themeFontSizeValue != 14) {
                  fontSizeChange('14');
                }
              }}
            >
              <dt>默认字体（推荐）</dt>
              <MyIcon
                type="icon-xuanzejiaobiao"
                isTheme={isFontSizeBool(14)}
                style={{
                  color: !isFontSizeBool(14) ? '#cbcbcb' : '',
                }}
              />
            </dl>

            <dl
              style={{
                fontSize: '16px',
                borderColor: isFontSizeBool(16) && returnThemeColor,
              }}
              onClick={() => {
                if (themeFontSizeValue != 16) {
                  fontSizeChange('16');
                }
              }}
            >
              <dt>字体：中</dt>
              <dd>建议您在分辨率1600以上的显示器使用</dd>
              <MyIcon
                type="icon-xuanzejiaobiao"
                isTheme={isFontSizeBool(16)}
                style={{
                  color: !isFontSizeBool(16) ? '#cbcbcb' : '',
                }}
              />
            </dl>

            <dl
              style={{
                fontSize: '18px',
                borderColor: isFontSizeBool(18) && returnThemeColor,
              }}
              onClick={() => {
                if (themeFontSizeValue != 18) {
                  fontSizeChange('18');
                }
              }}
            >
              <dt>字体：大</dt>
              <dd>建议您在分辨率1920以上的显示器使用</dd>
              <MyIcon
                type="icon-xuanzejiaobiao"
                isTheme={isFontSizeBool(18)}
                style={{
                  color: !isFontSizeBool(18) ? '#cbcbcb' : '',
                }}
              />
            </dl>
          </Space>
        </div>
      </ScrollBarLayout>
    </Drawer>
  );
};

export default connect(({ baseLogin }: any) => ({ baseLogin }))(SwitchTheme);
